#!/usr/bin/python3
import sys

strength = {
    'A': 'h',
    'K': 'i',
    'Q': 'k',
    'J': 'l',
    'T': 'm',
    '9': 'n',
    '8': 'o',
    '7': 'p',
    '6': 'q',
    '5': 'r',
    '4': 's',
    '3': 't',
    '2': 'u',
}

def get_type(hand):
    counts = {}
    for c in hand:
        counts[c] = counts.get(c, 0) + 1
    sort = sorted(counts.values(), reverse=True)
    if sort[0] == 5:
        return 'a'
    elif sort[0] == 4:
        return 'b'
    elif sort[0] == 3 and sort[1] == 2:
        return 'c'
    elif sort[0] == 3:
        return 'd'
    elif sort[0] == 2 and sort[1] == 2:
        return 'e'
    elif sort[0] == 2:
        return 'f'
    else:
        return 'g'

def get_strength(hand):
    return ''.join([strength[c] for c in hand])

def part1():
    print('part 1')
    hands = []
    for line in sys.stdin:
        hand, bid = line.strip().split(' ')
        hand_type = get_type(hand)
        hand_strength = get_strength(hand)
        hands.append((hand, bid, hand_type + hand_strength))
    sort = sorted(hands, key=lambda tup: tup[2], reverse=True)
    winnings = 0
    for i, (hand, bid, order) in enumerate(sort):
        winnings += (i + 1) * int(bid)
        print(i + 1, hand, bid, order)
    print(winnings)

strength_alt = {
    'A': 'h',
    'K': 'i',
    'Q': 'k',
    'T': 'l',
    '9': 'm',
    '8': 'n',
    '7': 'o',
    '6': 'p',
    '5': 'q',
    '4': 'r',
    '3': 's',
    '2': 't',
    'J': 'u',
}

def get_type_alt(hand):
    counts = {}
    for c in hand:
        counts[c] = counts.get(c, 0) + 1
    free = counts.get('J', 0)
    if free > 0:
        del counts['J']
    sort = sorted(counts.values(), reverse=True)
    if len(sort) == 0:
        sort.append(0)
    sort[0] += free
    if sort[0] == 5:
        return 'a'
    elif sort[0] == 4:
        return 'b'
    elif sort[0] == 3 and sort[1] == 2:
        return 'c'
    elif sort[0] == 3:
        return 'd'
    elif sort[0] == 2 and sort[1] == 2:
        return 'e'
    elif sort[0] == 2:
        return 'f'
    else:
        return 'g'

def get_strength_alt(hand):
    return ''.join([strength_alt[c] for c in hand])

def part2():
    print('part 2')
    hands = []
    for line in sys.stdin:
        hand, bid = line.strip().split(' ')
        hand_type = get_type_alt(hand)
        hand_strength = get_strength_alt(hand)
        hands.append((hand, bid, hand_type + hand_strength))
    sort = sorted(hands, key=lambda tup: tup[2], reverse=True)
    winnings = 0
    for i, (hand, bid, order) in enumerate(sort):
        winnings += (i + 1) * int(bid)
        print(i + 1, hand, bid, order)
    print(winnings)

if sys.argv[1] in '1':
    part1()
else:
    part2()
